package org.snail.proxy;

import org.snail.SnailClient;

/**
 * 代理工厂
 * <p>
 * Created by fish on 17/8/27.
 */
public class ProxyFactory<I> {

    /**
     * 客户端
     */
    private SnailClient client;

    /**
     * 接口名称
     */
    private Class<I> interfaceClass;

    /**
     * 是否同步(默认同步)
     */
    private boolean sync = true;

    /**
     * 分组
     */
    private String group;

    /**
     * 名称
     */
    private String providerName;

    /**
     * 版本
     */
    private String version;

    public ProxyFactory(Class<I> interfaceClass) {
        this.interfaceClass = interfaceClass;
    }

    /**
     * 构建对象方便以build模式加载信息
     *
     * @param interfaceClass
     */
    public static <I> ProxyFactory<I> factory(Class<I> interfaceClass) {
        ProxyFactory factory = new ProxyFactory(interfaceClass);
        return factory;
    }

    /**
     * 注入client
     *
     * @param client
     */
    public ProxyFactory<I> client(SnailClient client) {
        this.client = client;
        return this;
    }

    /**
     * 是否同步调用,默认同步调用
     *
     * @param sync
     */
    public ProxyFactory<I> sync(boolean sync) {
        this.sync = sync;
        return this;
    }

    /**
     * 分组
     *
     * @param group
     */
    public ProxyFactory<I> group(String group) {
        this.group = group;
        return this;
    }

    /**
     * 名称
     *
     * @param providerName
     */
    public ProxyFactory<I> providerName(String providerName) {
        this.providerName = providerName;
        return this;
    }

    /**
     * 版本
     *
     * @param version
     */
    public ProxyFactory<I> version(String version) {
        this.version = version;
        return this;
    }


    /**
     * 负载均衡算法
     */


    /**
     * 错误重试机制
     */


    /**
     * 根据接口获取实例化代理对象。
     */
    public I newProxyInstance() {
        if (sync) {
            return Proxies.newProxy(interfaceClass, new ProxySyncHandler(client, group, providerName, version));
        }
        return Proxies.newProxy(interfaceClass, new ProxyAsyncHandler(client));
    }

}
